<template>
  <div class="setting-content inside-comment">
    <el-scrollbar height="calc(100vh - 170px)">
      <h2 class="setting-header">
        <strong>考试管理</strong>
      </h2>
      <div class="top-btns">
        <SearchCmp v-if="searchCmpArray.length" :searchCmpArray="searchCmpArray" :searchForm="queryData" @onSubmit="getTableData" />
        <el-button class="add-button" type="primary" @click="addExam">创建考试</el-button>
      </div>
      <RuifoxTable
        :loading="tableLoading"
        :table-data="tableData"
        :field-list="fieldList"
        :default-index="true"
        :default-checkbox="true"
      >
        <template #default-checkbox="{ element }">
          <div class="table-div-check">
            <el-checkbox
              class="unmover"
              v-model="element.checked"
              @change="handleCheckTable(element.id)"
              size=""
            />
          </div>
        </template>

        <!-- 考试访问模式 -->
        <template #accessMode="{ element }">
          <div>
            <el-tag v-if="element.permissionConfig.accessMode == 'PUBLIC'" type="primary">完全公开</el-tag>
            <el-tag v-if="element.permissionConfig.accessMode == 'MEMBER'" type="primary">指定成员</el-tag>
            <el-tag v-if="element.permissionConfig.accessMode == 'PASSWORD'" type="primary">口令密码</el-tag>
            <el-tag v-if="element.permissionConfig.accessMode == 'EXCLUSIVE'" type="primary">专属考试</el-tag>
          </div>
        </template>
        
        <!-- 状态 -->
        <template #status="{ element }">
          <div>
            <el-tag v-if="element.status == 'UNSEALED'" type="primary">草稿</el-tag>
            <el-tag v-if="element.status == 'NORMAL'" type="success">已发布</el-tag>
            <el-tag v-if="element.status == 'DISABLE'" type="info">禁用</el-tag>
          </div>
        </template>

        <!-- 开始时间列 -->
        <template #startTime="{ element }">
          <span v-if="element.startTime && element.startTime != ''">{{ formatDate(element.startTime,"yyyy-MM-dd hh:mm") }}</span>
        </template>

        <!-- 结束时间列 -->
        <template #endTime="{ element }">
          <span v-if="element.endTime && element.endTime != ''">{{ formatDate(element.endTime,"yyyy-MM-dd hh:mm") }}</span>
        </template>

        <!-- 考试时长列 -->
        <template #duration="{ element }">
          <span v-if="!element.duration">-</span>
        </template>

        <!-- 操作列 -->
        <template #options="{ element }">
          <div class="table-td-option unmover">
            <el-button type="primary" link @click="editExam(element)">编辑</el-button>
            <el-button type="primary" link @click="copyExam(element)">复制</el-button>
            <el-button type="primary" link @click="viewExaminee(element)">查看考生</el-button>
            <el-dropdown>
              <span class="el-dropdown-link unmover">
                <i class="iconfont">&#xe78d;</i>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="extendExam(element)">延时</el-dropdown-item>
                  <el-dropdown-item v-if="element.status != 'UNSEALED'" @click="changeState(element,'UNSEALED(unsealed,未公布)')">设为草稿</el-dropdown-item>
                  <el-dropdown-item v-if="element.status != 'NORMAL'" @click="changeState(element,'NORMAL(normal,正常)')">发布</el-dropdown-item>
                  <el-dropdown-item v-if="element.status != 'DISABLE'" @click="changeState(element,'DISABLE(disable,禁用)')">禁用</el-dropdown-item>
                  <el-dropdown-item type="danger" @click="delExam(element)">删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </RuifoxTable>
      <PaginationView
        :isAffix = "false"
        :total="queryData.total"
        :pageSize="queryData.pageSize"
        :currentPage="queryData.currentPage"
        :allChoose="isAllChooseBtn"
        :pageChoose="isPageChooseBtn"
        :options="batchOptions"
        :checkedNum="checkedNum"
        :canChoose="queryData.total > 0"
        @changeSize="handleSizeChange"
        @currentChange="handleCurrentChange"
        @changePageChoose="handlePageChoose"
        @changeAllChoose="handleAllChoose"
        @invertChoose="handleInvertChoose"
        @checkOption="handleBatchOptions"
        @refreshList="getTableData"
        @cancelChoose="handleResetPagination"
        v-if="tableData.length > 0"
      />
      <!-- 创建 编辑考试  -->
      <el-drawer v-model="dialogVisible" :title="dialogTitle" size="730px" direction="ltr" :before-close="handleCloseDialog">
        <template #default >
          <div class="sync-exam-container">
            <div class="exam-container">
              <div class="menu-list">
                <div v-for="(item,index) in examArray" :key="item.id" @click="scrollToSection(index)"  class="step-item" :class="{ 'cur': activeIndex === index }">
                   {{item.label}}
                </div>
              </div>
              <div class="exam-draw" ref="contentRef" @scroll="handleScroll" style="width: 100%;height: 100%; overflow-y: auto;">
                <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px" class="exam-form" >
                  <!-- 考试设置  -->
                  <div class="exam-info" ref="sectionRef0">
                    <h3 class="info-title">考试设置</h3>
                    <el-form-item label="试卷名称" prop="name">
                      <el-input v-model="formData.name" placeholder="请输入试卷名称" />
                    </el-form-item>
                    <el-form-item label="说明" prop="description">
                      <el-input v-model="formData.description" placeholder="请输入试卷说明" />
                    </el-form-item>
                    <el-form-item label="业务标识" prop="businessKey">
                      <el-input v-model="formData.businessKey" placeholder="请输入业务标识" />
                    </el-form-item>
                    <!-- <el-form-item label="试卷规则" prop="paperConfig">
                      <el-button @click="addPaperRules" v-if="formData.paperConfig == ''">添加组卷规则</el-button>
                      <el-button @click="editPaperRules" v-else>设置组卷规则</el-button>
                    </el-form-item> -->
                    <!-- <el-form-item label="总分" prop="totalScore">
                      <el-input-number v-model="formData.totalScore" :min="1"  :step="1" :precision="0" />
                    </el-form-item>
                    <el-form-item label="及格分数" prop="qualifyScore">
                      <el-input-number v-model="formData.qualifyScore" :min="1" :step="1" :precision="0" />
                    </el-form-item>
                   -->
                    <el-form-item label="考试开始时间" prop="startTime">
                      <el-date-picker
                        v-model="formData.startTime"
                        type="datetime"
                        format="YYYY-MM-DD HH:mm:ss"
                        placeholder="选择考试开始时间"
                      />
                    </el-form-item>
                    <el-form-item label="考试结束时间" >
                      <el-date-picker
                        v-model="formData.endTime"
                        type="datetime"
                        format="YYYY-MM-DD HH:mm:ss"
                        placeholder="选择考试结束时间"
                        :disabled-date="disabledEndDate"
                      />
                      <el-button type="primary" @click="formData.endTime = '2050-01-01 00:00:00'">长期有效</el-button>
                    </el-form-item>
                    <el-form-item label="考试限时" prop="timeLimit">
                      <el-switch v-model="formData.timeLimit" />
                    </el-form-item>
                    <el-form-item label="考试时长" prop="duration" v-if="formData.timeLimit">
                      <el-input-number v-model="formData.duration" :min="1" :step="1" :precision="0" />
                      <span class="form-item-tip">（分钟）</span>
                    </el-form-item>
                    <el-form-item label="考试尝试次数" prop="tryCount">
                      <el-input-number v-model="formData.tryCount" :min="1" :step="1" :precision="0" />
                    </el-form-item>
                    <el-form-item label="答题模式" prop="answerMode">
                      <el-select v-model="formData.answerMode" placeholder="请选择答题模式" style="width: 240px">
                        <el-option label="逐题模式" value="ONE_BY_ONE" />
                        <el-option label="整卷模式" value="ALL_AT_ONCE" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="监考规则" prop="invigilatorConfig.invigilatorGroup">
                      <el-input v-model="formData.invigilatorConfig.invigilatorGroup" placeholder="请输入监考规则" />
                    </el-form-item>
                  </div>
                  <!-- 权限规则  -->
                  <div class="exam-info" ref="sectionRef1">
                    <h3 class="info-title">权限规则</h3>
                    <el-form-item label="考试访问模式" prop="permissionConfig.accessMode">
                      <el-select v-model="formData.permissionConfig.accessMode" placeholder="请选择考试访问模式" style="width: 240px">
                        <el-option
                          v-for="item in typeOption"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="报名开始时间" prop="enrollStartTime" v-if="formData.permissionConfig.accessMode == 'PUBLIC'">
                      <el-date-picker
                        v-model="formData.enrollStartTime"
                        type="datetime"
                        placeholder="选择报名开始时间"
                      />
                    </el-form-item>
                    <el-form-item label="报名结束时间" prop="enrollEndTime" v-if="formData.permissionConfig.accessMode == 'PUBLIC'">
                      <el-date-picker
                        v-model="formData.enrollEndTime"
                        type="datetime"
                        placeholder="选择报名结束时间"
                      />
                    </el-form-item>
                    <el-form-item label="其他用户查看" prop="visibilityForOutRangeUser">
                      <el-switch v-model="formData.permissionConfig.visibilityForOutRangeUser" />
                    </el-form-item>
                    <el-form-item label="口令" prop="permissionConfig.password" v-if="formData.permissionConfig.accessMode == 'PASSWORD'">
                      <el-input v-model="formData.permissionConfig.password" placeholder="请输入试卷口令" />
                    </el-form-item>
                    <el-form-item label="允许访问部门" prop="permanent" v-if="formData.permissionConfig.accessMode == 'MEMBER'">
                      <el-cascader :options="departTree" v-model="formData.permissionConfig.allowDepartments" clearable :props="props" :show-all-levels="false" popper-class="pid-cascader" placeholder="请选择部门" />
                        <!-- <template #default="{ data }">
                          <p>{{data.label}}</p>
                        </template> -->
                      <!-- </el-cascader> -->
                    </el-form-item>
                    <!-- 选择分组  -->
                    <el-form-item label="允许访问分组" prop="permanent" v-if="formData.permissionConfig.accessMode == 'MEMBER'">
                      <el-select
                        v-model="formData.permissionConfig.allowGroups"
                        style="width: 200px"
                        @change="handleReplyChange"
                        multiple 
                      >
                        <el-option
                          v-for="item in groupList"
                          :key="item.value"
                          :label="item.name"
                          :value="item.id"
                        />
                      </el-select>
                    </el-form-item>
                  </div>
                  <!-- 基本设置  -->
                  <div class="exam-info" ref="sectionRef2"> 
                    <h3 class="info-title">基本设置</h3>
                    <!-- 设备使用限制  -->
                    <el-form-item label="设备使用限制" prop="allowPc">
                      <el-switch v-model="formData.antiCheatingConfig.antiCheatBaseConfig.deviceUseRestriction.open" />
                    </el-form-item>
                    <div v-if="formData.antiCheatingConfig.antiCheatBaseConfig.deviceUseRestriction.open">
                      <div class="form-row">
                        <el-form-item class="row-item" label="允许电脑端">
                          <el-switch v-model="formData.antiCheatingConfig.antiCheatBaseConfig.deviceUseRestriction.allowPc" />
                        </el-form-item>
                        <el-form-item class="row-item" label="允许手机端">
                          <el-switch v-model="formData.antiCheatingConfig.antiCheatBaseConfig.deviceUseRestriction.allowMobile" />
                        </el-form-item>
                      </div>
                      <el-divider style="margin-bottom: 15px;"></el-divider>
                    </div>
                    <!-- 设备切换限制  -->
                    <div class="form-row">
                      <el-form-item class="row-item" label="设备使用限制">
                        <el-switch v-model="formData.antiCheatingConfig.antiCheatBaseConfig.deviceSwitchingRestriction.open" />
                      </el-form-item>
                      <el-form-item class="row-item" label="设备切换次数" prop="maxSwitchCount" v-if="formData.antiCheatingConfig.antiCheatBaseConfig.deviceSwitchingRestriction.open">
                        <el-input-number v-model="formData.antiCheatingConfig.antiCheatBaseConfig.deviceSwitchingRestriction.maxSwitchCount" :min="2" :max="10" :step="1" :precision="0" />
                      </el-form-item>
                    </div>
                    <el-divider style="margin-bottom: 15px;" v-if="formData.antiCheatingConfig.antiCheatBaseConfig.deviceSwitchingRestriction.open"></el-divider>
                    <!-- IP切换限制  -->
                    <div class="form-row">
                      <el-form-item class="row-item" label="允许IP切换" prop="allowIpChange">
                        <el-switch v-model="formData.antiCheatingConfig.antiCheatBaseConfig.ipSwitchingRestriction.open" />
                      </el-form-item>
                      <el-form-item class="row-item" label="IP切换次数" prop="maxIpChangeCount" v-if="formData.antiCheatingConfig.antiCheatBaseConfig.ipSwitchingRestriction.open">
                        <el-input-number v-model="formData.antiCheatingConfig.antiCheatBaseConfig.maxIpChangeCount" :min="2" :max="10" :step="1" :precision="0" />
                      </el-form-item>
                    </div>
                    <el-divider style="margin-bottom: 15px;" v-if="formData.antiCheatingConfig.antiCheatBaseConfig.ipSwitchingRestriction.open"></el-divider>

                    <!-- 试卷控制  -->
                    <el-form-item label="试卷控制" prop="allowIpChange">
                      <el-switch v-model="formData.antiCheatingConfig.antiCheatBaseConfig.additionalRestriction.open" />
                    </el-form-item>
                    <div v-if="formData.antiCheatingConfig.antiCheatBaseConfig.additionalRestriction.open">
                      <div class="form-row">
                        <el-form-item class="row-item" label="禁止复制粘贴" prop="copyPrevent" >
                          <el-switch v-model="formData.antiCheatingConfig.antiCheatBaseConfig.additionalRestriction.copyPrevent" />
                        </el-form-item>
                        <el-form-item class="row-item" label="水印" prop="watermark" >
                          <el-switch v-model="formData.antiCheatingConfig.antiCheatBaseConfig.additionalRestriction.watermark" />
                        </el-form-item>
                      </div>
                      <el-form-item label="全屏显示" prop="fullScreen" >
                        <el-switch v-model="formData.antiCheatingConfig.antiCheatBaseConfig.additionalRestriction.fullScreen" />
                      </el-form-item>
                      <el-divider style="margin-bottom: 15px;"></el-divider>
                    </div>
                  </div>
                  <!-- 监控设置  -->
                  <div class="exam-info" ref="sectionRef3"> 
                    <h3 class="info-title">监控设置</h3>
                    <!-- 屏幕&摄像头监控设置 -->
                    <el-form-item label="设备监控" prop="allowPc">
                      <el-switch v-model="formData.antiCheatingConfig.antiCheatMonitorConfig.screenAndCameraMonitorConfig.open" />
                    </el-form-item>
                    <div v-if="formData.antiCheatingConfig.antiCheatMonitorConfig.screenAndCameraMonitorConfig.open">
                      <div class="form-row">
                        <el-form-item class="row-item" label="屏幕实时监控" >
                          <el-switch v-model="formData.antiCheatingConfig.antiCheatMonitorConfig.screenAndCameraMonitorConfig.screenRealTimeStream" />
                        </el-form-item>
                        <el-form-item class="row-item" label="屏幕录制" >
                          <el-switch v-model="formData.antiCheatingConfig.antiCheatMonitorConfig.screenAndCameraMonitorConfig.screenRecordOpen" />
                        </el-form-item>
                        <el-form-item class="row-item" label="摄像头实时监控" >
                          <el-switch v-model="formData.antiCheatingConfig.antiCheatMonitorConfig.screenAndCameraMonitorConfig.cameraRealTimeStream" />
                        </el-form-item>
                        <el-form-item class="row-item" label="摄像头录制" >
                          <el-switch v-model="formData.antiCheatingConfig.antiCheatMonitorConfig.screenAndCameraMonitorConfig.cameraRecordOpen" />
                        </el-form-item>
                      </div>
                      <el-divider style="margin-bottom: 15px;"></el-divider>
                    </div>
                    <!-- 行为监控配置 -->
                    <el-form-item label="行为监控" >
                      <el-switch v-model="formData.antiCheatingConfig.antiCheatMonitorConfig.behaviorMonitoringConfig.open" />
                    </el-form-item>
                    <div v-if="formData.antiCheatingConfig.antiCheatMonitorConfig.behaviorMonitoringConfig.open">
                      <el-form-item class="row-item" label="行为监控间隔" >
                        <el-input-number v-model="formData.antiCheatingConfig.antiCheatMonitorConfig.behaviorMonitoringConfig.behaviorMonitoringInterval" :min="2" :step="1" :precision="0" />
                        <span class="form-item-tip">（分钟）</span>
                      </el-form-item>
                      <el-form-item class="row-item" label="行为监控阈值" >
                        <el-input-number v-model="formData.antiCheatingConfig.antiCheatMonitorConfig.behaviorMonitoringConfig.behaviorMonitoringThreshold" :min="2" :step="1" :precision="0" />
                      </el-form-item>
                      <el-divider style="margin-bottom: 15px;"></el-divider>
                    </div>
                    <!-- 人脸监控配置 -->
                    <el-form-item label="人脸监控" >
                      <el-switch v-model="formData.antiCheatingConfig.antiCheatMonitorConfig.faceMonitoringConfig.open" />
                    </el-form-item>
                    <div v-if="formData.antiCheatingConfig.antiCheatMonitorConfig.faceMonitoringConfig.open">
                      <el-form-item class="row-item" label="人脸监控间隔" >
                        <el-input-number v-model="formData.antiCheatingConfig.antiCheatMonitorConfig.faceMonitoringConfig.faceMonitoringInterval" :min="2" :step="1" :precision="0" />
                        <span class="form-item-tip">（分钟）</span>
                      </el-form-item>
                      <el-form-item class="row-item" label="人脸监控阈值" >
                        <el-input-number v-model="formData.antiCheatingConfig.antiCheatMonitorConfig.faceMonitoringConfig.faceMonitoringThreshold" :min="2" :step="1" :precision="0" />
                      </el-form-item>
                      <el-divider style="margin-bottom: 15px;"></el-divider>
                    </div>
                    <!-- 声音监控配置 -->
                    <el-form-item label="声音监控" >
                      <el-switch v-model="formData.antiCheatingConfig.antiCheatMonitorConfig.soundMonitoringConfig.open" />
                    </el-form-item>
                    <div v-if="formData.antiCheatingConfig.antiCheatMonitorConfig.soundMonitoringConfig.open">
                      <el-form-item class="row-item" label="声音监控间隔" >
                        <el-input-number v-model="formData.antiCheatingConfig.antiCheatMonitorConfig.soundMonitoringConfig.soundMonitoringInterval" :min="2" :step="1" :precision="0" />
                        <span class="form-item-tip">（分钟）</span>
                      </el-form-item>
                      <el-form-item class="row-item" label="声音监控阈值" >
                        <el-input-number v-model="formData.antiCheatingConfig.antiCheatMonitorConfig.soundMonitoringConfig.soundMonitoringThreshold" :min="2" :step="1" :precision="0" />
                      </el-form-item>
                      <el-divider style="margin-bottom: 15px;"></el-divider>
                    </div>
                    <!-- 无操作监控配置 -->
                    <el-form-item label="无操作监控" >
                      <el-switch v-model="formData.antiCheatingConfig.antiCheatMonitorConfig.noActionMonitoringConfig.open" />
                    </el-form-item>
                    <div v-if="formData.antiCheatingConfig.antiCheatMonitorConfig.noActionMonitoringConfig.open">
                      <el-form-item class="row-item" label="无操作监控间隔" >
                        <el-input-number v-model="formData.antiCheatingConfig.antiCheatMonitorConfig.noActionMonitoringConfig.noActionMonitoringInterval" :min="1" :step="1" :precision="0" />
                        <span class="form-item-tip">（分钟）</span>
                      </el-form-item>
                      <el-form-item class="row-item" label="最多持续时间" >
                        <el-input-number v-model="formData.antiCheatingConfig.antiCheatMonitorConfig.noActionMonitoringConfig.noActionMaxDuration" :min="2" :step="1" :precision="0" />
                        <span class="form-item-tip">（分钟）</span>
                      </el-form-item>
                    </div>
                    <el-divider style="margin-bottom: 15px;" v-if="formData.antiCheatingConfig.antiCheatMonitorConfig.noActionMonitoringConfig.open"></el-divider>
                    <!-- 窗口切换监控配置 -->
                    <el-form-item label="窗口切换监控" >
                      <el-switch v-model="formData.antiCheatingConfig.antiCheatMonitorConfig.windowsSwitchMonitoringConfig.open" />
                    </el-form-item>
                    <div v-if="formData.antiCheatingConfig.antiCheatMonitorConfig.windowsSwitchMonitoringConfig.open">
                      <div class="form-row">
                        <el-form-item class="row-item" label="窗口切换间隔" >
                          <el-input-number v-model="formData.antiCheatingConfig.antiCheatMonitorConfig.windowsSwitchMonitoringConfig.windowsSwitchMonitoringInterval" :min="1" :step="1" :precision="0" />
                        </el-form-item>
                        <el-form-item class="row-item" label="最大切换次数" >
                          <el-input-number v-model="formData.antiCheatingConfig.antiCheatMonitorConfig.windowsSwitchMonitoringConfig.windowsSwitchMaxCount" :min="2" :step="1" :precision="0" />
                        </el-form-item>
                      </div>
                      <el-divider style="margin-bottom: 15px;"></el-divider>
                    </div>
                  </div>
                  <!-- 阅卷设置  -->
                  <div class="exam-info" ref="sectionRef4"> 
                    <h3 class="info-title">阅卷设置</h3>
                    <el-form-item label="答题模式" prop="markingConfig.markingType" >
                      <el-select v-model="formData.markingConfig.markingType" placeholder="请选择答题模式" style="width: 240px">
                        <el-option label="实时" value="REALTIME" />
                        <el-option label="统一阅卷" value="UNIFIED" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="阅卷开始时间" prop="markingStartTime">
                      <el-date-picker
                        v-model="formData.markingStartTime"
                        type="datetime"
                        placeholder="选择阅卷开始时间"
                      />
                    </el-form-item>
                    <el-form-item label="阅卷结束时间" prop="markingEndTime">
                      <el-date-picker
                        v-model="formData.markingEndTime"
                        type="datetime"
                        placeholder="选择阅卷结束时间"
                      />
                    </el-form-item>
                    <el-form-item label="隐藏答题人姓名" prop="hideAnswererName" >
                      <el-switch v-model="formData.antiCheatingConfig.markingConfig.hideAnswererName" />
                    </el-form-item>
                    <el-form-item label="阅卷方式" prop="markingConfig.markingMethod" >
                      <el-select v-model="formData.markingConfig.markingMethod" placeholder="请选择阅卷方式" style="width: 240px">
                        <el-option label="整卷" value="WHOLE_PAPER" />
                        <el-option label="按大题" value="QUESTION_BASIS" />
                        <el-option label="按小题" value="SUB_QUESTION_BASIS" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="大题阅卷人" prop="markingConfig.questionBasicMarkingUsers" v-if="formData.markingConfig.markingMethod == QUESTION_BASIS" >
                      <el-select v-model="formData.markingConfig.questionBasicMarkingUsers" placeholder="请选择大题阅卷人" style="width: 240px">
                        <el-option label="张三" value="1" />
                        <el-option label="李四" value="2" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="小题阅卷人" prop="markingConfig.subQuestionBasicMarkingUsers" v-if="formData.markingConfig.markingMethod == SUB_QUESTION_BASIS" >
                      <el-select v-model="formData.markingConfig.subQuestionBasicMarkingUsers" placeholder="请选择小题阅卷人" style="width: 240px">
                        <el-option label="张三" value="1" />
                        <el-option label="李四" value="2" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="阅卷人" prop="markingUsers">
                      <el-select v-model="formData.markingConfig.markingUsers" placeholder="请选择阅卷人" style="width: 240px">
                        <el-option label="张三" value="1" />
                        <el-option label="李四" value="2" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="阅卷分配方式" prop="markingConfig.assignStrategy">
                      <el-select v-model="formData.markingConfig.assignStrategy" placeholder="请选择阅卷管理员" style="width: 240px">
                        <el-option label="平均分配" value="AVERAGE" />
                        <el-option label="自由阅卷" value="FREE" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="阅卷管理员" prop="markingConfig.markingAdmins">
                      <el-select v-model="formData.markingConfig.markingAdmins" multiple  placeholder="请选择阅卷管理员" style="width: 240px" @change="setMarkAdmin">
                        <el-option label="张三" value="1" />
                        <el-option label="李四" value="2" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="多轮评卷" prop="faceCheckOpen" >
                      <el-switch v-model="formData.markingConfig.multiRound" />
                    </el-form-item>
                    <el-form-item label="评卷轮次" prop="markingRound" >
                      <el-input-number v-model="formData.markingConfig.markingRound" :min="1" :max="10" :step="1" :precision="0" />
                    </el-form-item>
                    <el-form-item label="赋分方式" prop="scoringMode" v-if="formData.markingConfig.markingRound > 1">
                      <el-select v-model="formData.markingConfig.scoringMode" placeholder="请选择赋分方式" style="width: 240px" >
                        <el-option label="高权重用户为准" value="WEIGHTED_MAX" />
                        <el-option label="加权平均分数" value="WEIGHTED_AVERAGE" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="超时自动回收" prop="autoRecycle" >
                      <el-switch v-model="formData.markingConfig.autoRecycle" />
                    </el-form-item>
                    <el-form-item label="自动回收时间" prop="autoRecycleTime" v-if="formData.markingConfig.autoRecycle">
                      <el-input-number v-model="formData.markingConfig.autoRecycleTime" :min="1" :max="10" :step="1" :precision="0" />
                      <span class="form-item-tip">（分钟）</span>
                    </el-form-item>
                  </div>
                  <!-- 考试结果展示设置  -->
                  <div class="exam-info" ref="sectionRef5"> 
                    <h3 class="info-title">考试结果</h3>
                    <el-form-item label="显示成绩" prop="showScore" >
                      <el-switch v-model="formData.resultDisplayConfig.showScore" />
                    </el-form-item>
                    <el-form-item label="显示正确答案" prop="showCorrectAnswer" >
                      <el-switch v-model="formData.resultDisplayConfig.showCorrectAnswer" />
                    </el-form-item>
                    <el-form-item label="显示答题卡" prop="showAnswerCard" >
                      <el-switch v-model="formData.resultDisplayConfig.showAnswerCard" />
                    </el-form-item>
                    <el-form-item label="显示答案" prop="showAnswer" >
                      <el-switch v-model="formData.resultDisplayConfig.showAnswer" />
                    </el-form-item>
                  </div>
                  <!-- 证书规则设置  -->
                  <div class="exam-info" ref="sectionRef6"> 
                    <h3 class="info-title">
                      <p>证书规则</p>
                      <el-button type="primary" @click="addCertificate">添加</el-button>
                    </h3>
                    <div class="certificate-item" v-for="(item,index) in formData.certificateConfigs" :key="index">
                      <div class="form-row">
                        <el-form-item label="起始分数" prop="beginScore" >
                          <el-input-number v-model="item.beginScore" :min="1" :step="1" :precision="0" />
                        </el-form-item>
                        <el-icon @click="delcertificate(index)" class="del-icon"><Delete /></el-icon>
                      </div>
                     
                      <!-- <el-form-item label="起始分数包含" prop="includeBeginScore" >
                        <el-switch v-model="item.includeBeginScore" />
                      </el-form-item> -->
                      <el-form-item label="结束分数" prop="endScore" >
                        <el-input-number v-model="item.endScore" :min="1" :step="1" :precision="0" />
                      </el-form-item>
                      <!-- <el-form-item label="结束分数包含" prop="includeEndScore" >
                        <el-switch v-model="item.includeEndScore" />
                      </el-form-item> -->
                      <el-form-item label="选择证书" prop="certificateTemplateId" >
                        <el-select v-model="formData.markingConfig.certificateTemplateId" placeholder="请选择证书" style="width: 240px">
                          <el-option label="初级证书" value="1" />
                          <el-option label="中级证书" value="2" />
                          <el-option label="高级证书" value="3" />
                        </el-select>
                      </el-form-item>
                    </div>
                  </div>
                  <!-- 组卷规则设置  -->
                  <div class="exam-info" ref="sectionRef7"> 
                    <h3 class="info-title">组卷规则</h3>
                    <el-form-item label="试卷名称" prop="label">
                      <el-input v-model="formData.paperConfig.label" placeholder="请输入试卷名称" />
                    </el-form-item>
                    <el-form-item label="组卷开始时间" >
                      <el-date-picker
                        v-model="formData.autoComposingTime"
                        type="datetime"
                        format="YYYY-MM-DD HH:mm:ss"
                        placeholder="选择自动组卷开始时间"
                      />
                    </el-form-item>
                    <el-form-item label="组卷方式" prop="randomWay">
                      <el-select v-model="formData.paperConfig.randomWay" placeholder="请选择随机组卷方式" style="width: 240px">
                        <el-option label="基础试卷组卷" value="1" />
                        <el-option label="自定义条件组卷" value="2" />
                      </el-select>
                    </el-form-item>
                    <!-- 选择已有试卷  -->
                    <div  v-if="formData.paperConfig.randomWay == 1">
                      <el-form-item label="选择试卷" prop="originalIdList" >
                        <el-select v-model="formData.paperConfig.originalIdList" multiple placeholder="请选择试卷" style="width: 240px">
                          <el-option label="试卷1" value="1" />
                          <el-option label="试卷2" value="2" />
                        </el-select>
                      </el-form-item>
                      <el-form-item label="题目是否随机" prop="isTitleRandom">
                        <el-switch v-model="formData.paperConfig.isTitleRandom" />
                      </el-form-item>
                    </div>
                    <!-- 自定义组卷  -->
                    <div  v-if="formData.paperConfig.randomWay == 2">
                      <el-form-item label="选择题库" prop="bankIdList">
                        <el-select v-model="formData.paperConfig.bankIdList" placeholder="请选择题库" style="width: 240px">
                          <el-option label="题库1" value="1" />
                          <el-option label="题库2" value="2" />
                        </el-select>
                      </el-form-item>
                      <!-- 题目总分 根据题组的设置信息自动计算  -->
                      <el-form-item label="总分" prop="totalScore">
                        <el-input-number v-model="formData.totalScore" :min="1"  :step="1" :precision="0" disabled/>
                      </el-form-item>
                      <el-form-item label="及格分数" prop="qualifyScore">
                        <el-input-number v-model="formData.qualifyScore" :min="1" :step="1" :precision="0" />
                      </el-form-item>
                      <el-form-item label="及格分占比" prop="passingScoreRate">
                        <el-input-number v-model="formData.passingScoreRate" :min="1" :step="1" :precision="0" />
                      </el-form-item>
                      <div class="question-group-config">
                        <el-divider />
                        <!-- 题组参数设置  -->
                        <div class="tip">
                          <p>题组设置</p>
                          <el-button type="primary" @click="addQuestionGroup" class="add-but">添加题组</el-button>
                        </div>
                        <div class="item-set-config" v-for="(item, index) in formData.paperConfig.customizationVo.itemSetConfigVoList" :key="index">
                          <div class="form-row">
                            <el-form-item label="题组名称" prop="setName">
                              <el-input v-model="item.setName" placeholder="请输入题组名称" style="width: 200px;"/>
                            </el-form-item>
                            <el-icon @click="delQuestionGroup(index)" class="del-icon"><Delete /></el-icon>
                          </div>
                          <div class="form-row">
                            <el-form-item class="row-item" label="题目数量" prop="itemNum">
                              <el-input-number v-model="item.itemNum" :min="1" :step="1" :precision="0" />
                            </el-form-item>
                            <el-form-item class="row-item" label="每题分数" prop="itemScore">
                              <el-input-number v-model="item.itemScore" :min="1" :step="1" :precision="0" />
                            </el-form-item>
                            <el-form-item  class="row-item" label="题型" prop="typeId">
                              <el-select v-model="item.typeId" placeholder="请选择题型" style="width: 160px">
                                <el-option label="单选题" value="1" />
                                <el-option label="多选题" value="2" />
                                <el-option label="判断题" value="3" />
                                <el-option label="填空题" value="4" />
                                <el-option label="简答题" value="5" />
                              </el-select>
                            </el-form-item>
                            <el-form-item  class="row-item" label="题目难度" prop="difficulty">
                              <el-select v-model="item.difficulty" placeholder="请选择题目难度" style="width: 160px">
                                <el-option label="简单" value="1" />
                                <el-option label="中等" value="2" />
                                <el-option label="困难" value="3" />
                              </el-select>
                            </el-form-item>
                          </div>
                         
                          <el-form-item label="是否仲裁" prop="useArbitration">
                            <el-switch v-model="item.useArbitration" />
                          </el-form-item>
                          <el-form-item label="仲裁分数" prop="arbitrationScore" v-if="item.useArbitration">
                            <el-input-number v-model="item.arbitrationScore" :min="1" :step="1" :precision="0" />
                          </el-form-item>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="flex-box" :style="flexBoxStyle"></div>
                </el-form>
              </div>
            </div>
          </div>
        </template>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="stagingSubmit">暂存</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </span>
        </template>
      </el-drawer>

      <!-- 同步考试配置  -->
      <el-drawer v-model="editExamDialog" size="700px" title="同步考试配置" direction="ltr" :before-close="handleCloseDialog">
        <template #default >
          <div class="sync-exam-container">
            <div class="tip">批量同步考试配置仅能更改通用属性，同时更改后会覆盖原有考试配置，请谨慎操作。</div> 
            <!-- <h3>已选试卷</h3>
            <div class="exam-list">
              <p v-for="item in checkedList" :key="">{{item.name}}</p>
            </div> -->
            <div class="exam-container">
              <div class="menu-list" >
                <div v-for="(item,index) in syncArray" :key="item.id" @click="scrollToSection(index)"  class="step-item" :class="{ 'cur': activeIndex === index }">
                  {{item.label}}
                </div>
              </div>
              <div class="exam-draw tips" ref="asyncRef" @scroll="handleScroll" style="height: 100%; overflow-y: auto;">
                <el-form  ref="ayncFormRef" :model="syncForm" :rules="rules" label-width="100px" class="exam-form" >
                  <!-- 考试设置  -->
                  <div class="exam-info" ref="syncSectionRef0">
                    <h3 class="info-title">考试设置</h3>
                    <el-form-item label="考试开始时间" >
                      <el-date-picker
                        v-model="syncForm.startTime"
                        type="datetime"
                        format="YYYY-MM-DD HH:mm:ss"
                        placeholder="选择考试开始时间"
                      />
                    </el-form-item>
                    <el-form-item label="考试结束时间" >
                      <el-date-picker
                        v-model="syncForm.endTime"
                        type="datetime"
                        format="YYYY-MM-DD HH:mm:ss"
                        placeholder="选择考试结束时间"
                        :disabled-date="disabledEndDate"
                      />
                    </el-form-item>
                    <el-form-item label="考试限时" prop="timeLimit">
                      <el-switch v-model="syncForm.timeLimit" />
                    </el-form-item>
                    <el-form-item label="考试时长" prop="duration" v-if="syncForm.timeLimit">
                      <el-input-number v-model="syncForm.duration" :min="1" :step="1" :precision="0" />
                    </el-form-item>
                    <el-form-item label="答题模式" prop="answerMode">
                      <el-select v-model="syncForm.answerMode" placeholder="请选择答题模式" style="width: 240px">
                        <el-option label="逐题模式" value="ONE_BY_ONE" />
                        <el-option label="整卷模式" value="ALL_AT_ONCE" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="考试访问模式" prop="accessMode">
                      <el-select v-model="syncForm.accessMode" placeholder="请选择考试访问模式" style="width: 240px">
                        <el-option
                          v-for="item in typeOption"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </div>
                  <!-- 基本设置 -->
                  <div class="exam-info" ref="syncSectionRef1"> 
                    <h3 class="info-title">基本设置</h3>
                    <el-form-item label="允许电脑端" prop="allowPc">
                      <el-switch v-model="syncForm.antiCheatingConfig.antiCheatBaseConfig.allowPc" />
                    </el-form-item>
                    <el-form-item label="允许手机端" prop="allowMobile">
                      <el-switch v-model="syncForm.antiCheatingConfig.antiCheatBaseConfig.allowMobile" />
                    </el-form-item>
                    <el-form-item label="允许设备切换" prop="allowDeviceSwitch">
                      <el-switch v-model="syncForm.antiCheatingConfig.antiCheatBaseConfig.allowDeviceSwitch" />
                    </el-form-item>
                    <el-form-item label="设备切换次数" prop="maxSwitchCount" v-if="syncForm.antiCheatingConfig.antiCheatBaseConfig.allowDeviceSwitch">
                      <el-input-number v-model="syncForm.antiCheatingConfig.antiCheatBaseConfig.maxSwitchCount" :min="1" :max="10" :step="1" :precision="0" />
                    </el-form-item>
                    <el-form-item label="允许IP切换" prop="allowIpChange">
                      <el-switch v-model="syncForm.antiCheatingConfig.antiCheatBaseConfig.allowIpChange" />
                    </el-form-item>
                    <el-form-item label="IP切换次数" prop="maxIpChangeCount" v-if="syncForm.antiCheatingConfig.antiCheatBaseConfig.allowIpChange">
                      <el-input-number v-model="syncForm.antiCheatingConfig.antiCheatBaseConfig.maxIpChangeCount" :min="1" :max="10" :step="1" :precision="0" />
                    </el-form-item>
                    <el-form-item label="禁止复制粘贴" prop="copyPrevent" >
                      <el-switch v-model="syncForm.antiCheatingConfig.antiCheatBaseConfig.copyPrevent" />
                    </el-form-item>
                    <el-form-item label="水印" prop="watermark" >
                      <el-switch v-model="syncForm.antiCheatingConfig.antiCheatBaseConfig.watermark" />
                    </el-form-item>
                    <el-form-item label="全屏显示" prop="fullScreen" >
                      <el-switch v-model="syncForm.antiCheatingConfig.antiCheatBaseConfig.fullScreen" />
                    </el-form-item>
                  </div>
                  <!-- 防作弊设置 -->
                  <div class="exam-info" ref="syncSectionRef2"> 
                    <h3 class="info-title">防作弊设置</h3>
                    <el-form-item label="屏幕记录" prop="screenRecordOpen" >
                      <el-switch v-model="syncForm.antiCheatingConfig.antiCheatMonitorConfig.screenRecordOpen" />
                    </el-form-item>
                    <el-form-item label="辅助监控器" prop="requireAuxiliaryMonitor" >
                      <el-switch v-model="syncForm.antiCheatingConfig.antiCheatMonitorConfig.requireAuxiliaryMonitor" />
                    </el-form-item>
                    <el-form-item label="人脸验证" prop="faceCheckOpen" >
                      <el-switch v-model="syncForm.antiCheatingConfig.antiCheatMonitorConfig.faceCheckOpen" />
                    </el-form-item>
                    <el-form-item label="考中人脸验证" prop="faceCheckInterval" >
                      <el-switch v-model="syncForm.antiCheatingConfig.antiCheatMonitorConfig.faceCheckInterval" />
                    </el-form-item>
                    <el-form-item label="验证时间" prop="faceCheckThreshold" v-if="syncForm.antiCheatingConfig.antiCheatMonitorConfig.faceCheckInterval">
                      <span>每&nbsp;</span>
                      <el-input-number v-model="syncForm.antiCheatingConfig.antiCheatMonitorConfig.faceCheckThreshold" :min="1" :max="10" :step="1" :precision="0" />
                      <span>（分钟）</span>
                    </el-form-item>
                    <el-form-item label="无操作检测" prop="noActionMonitorOpen" >
                      <el-switch v-model="syncForm.antiCheatingConfig.antiCheatMonitorConfig.noActionMonitorOpen" />
                    </el-form-item>
                    <el-form-item label="无操作时间" prop="noActionMaxDuration" >
                      <el-input-number v-model="syncForm.antiCheatingConfig.antiCheatMonitorConfig.noActionMaxDuration" :min="1" :max="10" :step="1" :precision="0" />
                      <span>（分钟）</span>
                    </el-form-item>
                    <el-form-item label="切屏检测" prop="windowsSwitchMonitorOpen" >
                      <el-switch v-model="syncForm.antiCheatingConfig.antiCheatMonitorConfig.windowsSwitchMonitorOpen" />
                    </el-form-item>
                    <el-form-item label="最大切屏次数" prop="windowsSwitchMaxCount" >
                      <el-input-number v-model="syncForm.antiCheatingConfig.antiCheatMonitorConfig.windowsSwitchMaxCount" :min="1" :max="10" :step="1" :precision="0" />
                    </el-form-item>
                  </div>
                  <!-- 考试结果展示设置  -->
                  <div class="exam-info" ref="syncSectionRef3"> 
                    <h3 class="info-title">考试结果</h3>
                    <el-form-item label="显示成绩" prop="showScore" >
                      <el-switch v-model="syncForm.resultDisplayConfig.showScore" />
                    </el-form-item>
                    <el-form-item label="显示正确答案" prop="showCorrectAnswer" >
                      <el-switch v-model="syncForm.resultDisplayConfig.showCorrectAnswer" />
                    </el-form-item>
                    <el-form-item label="显示答题卡" prop="showAnswerCard" >
                      <el-switch v-model="syncForm.resultDisplayConfig.showAnswerCard" />
                    </el-form-item>
                    <el-form-item label="显示答案" prop="showAnswer" >
                      <el-switch v-model="syncForm.resultDisplayConfig.showAnswer" />
                    </el-form-item>
                  </div>
                </el-form>
              </div>
            </div>
          </div>
        </template>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editExamDialog = false">取消</el-button>
            <el-button type="primary" @click="postSync">确认</el-button>
          </span>
        </template>
      </el-drawer>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed, watch } from "vue";
import { useRouter } from "vue-router";
import { formatDate } from '@/utils/tools'
import { 
  selectExamPageExam,
  createExam,
  deleteExamExam,
  changeExamStatusExam,
  syncExamsConfigExam,
  updateExam,
  copyAndNewExam,
  checkPaperConfigExam,
  stagingExam
 } from "@/api/examination";
import { tableList as mixTable } from '@ruifox-cms/utils'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDepartTree } from "@/api/depart";
import { pagingGroup } from "@/api/group";
import { Delete } from '@element-plus/icons-vue';

const router = useRouter();
const viewExaminee = (item) => {
  router.push({ 
    path: '/exam/examinee', 
    query: { 
      id: item.id,
      name: item.name
    } 
  });
}
const statusOption = ref([
  { label: "未公开", value: 'UNSEALED' },
  { label: "正常", value: 'NORMAL' },
  { label: "禁用", value: 'DISABLE' },
]);
const typeOption = ref([
  { label: "完全公开", value: 'PUBLIC' },
  { label: "指定成员", value: 'MEMBER' },
  { label: "口令密码", value: 'PASSWORD' },
  { label: "专属考试", value: 'EXCLUSIVE' },
]);
const searchCmpArray = ref([
  { label: '考试状态', key: 'status', form_type: 'select', options: statusOption.value },
  { label: '考试访问模式', key: 'accessMode', form_type: 'select', options: typeOption.value },
  { label: '考试名称', key: 'name'}
])
const examArray = ref([
  { id: 0, label: '考试信息'},
  { id: 1, label: '权限规则'},
  { id: 2, label: '基础设置'},
  { id: 3, label: '防作弊设置'},
  { id: 4, label: '阅卷设置'},
  { id: 5, label: '考试结果'},
  { id: 6, label: '证书规则'},
  { id: 7, label: '组卷规则'},
])
const syncArray = ref([
  { id: 0, label: '考试信息'},
  { id: 1, label: '基础设置'},
  { id: 2, label: '防作弊设置'},
  { id: 3, label: '考试结果'},
])
const {
  queryData,
  tableData,
  tableLoading,
  checkedNum,
  isAllChooseBtn,
  isPageChooseBtn,
  checkedList,
  getTableData,
  // handleSearch,
  handleCurrentChange,
  handleSizeChange,
  handlePageChoose,
  handleAllChoose,
  handleInvertChoose,
  handleCheckTable,
  handleResetPagination,
} = mixTable({
  getListApi: selectExamPageExam,
});
const defaultQuery = reactive({
  currentPage: 1,
  pageSize: 10,
  total:10,
  sort:"",
  order: "",
  name:"",
  status: "",
  openType: "",
  businessKey: "",
  timeLimit: "",
  creator: ""
});

Object.assign(queryData, defaultQuery);

//增加题组
const addQuestionGroup = () => {
  formData.value.paperConfig.customizationVo.itemSetConfigVoList.push({
    setName: "",
    itemNum: 0,
    itemScore: 1,
    difficultyLevel: 0,
    useArbitration: false,
    arbitrationScore: 0,
  })
}
//删除题组
const delQuestionGroup = (index) => {
  formData.value.paperConfig.customizationVo.itemSetConfigVoList.splice(index, 1);
};

//表单校验
const rules = {
  name: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  'permissionConfig.accessMode': [{ required: true, message: '请选择考试访问模式', trigger: 'change' }],
  businessKey: [{ required: true, message: '请输入业务关键', trigger: 'blur' }],
  answerMode: [{ required: true, message: '请选择答题模式', trigger: 'change' }],
  accessMode: [{ required: true, message: '请选择考试访问模式', trigger: 'change' }],
  'invigilatorConfig.invigilatorGroup': [{ required: true, message: '请输入监考规则', trigger: 'blur' }],
  'permissionConfig.password': [{ required: true, message: '请输入口令', trigger: 'blur' }],
  'markingConfig.markingType': [{ required: true, message: '请选择评卷类型', trigger: 'change' }],
  'markingConfig.markingMethod': [{ required: true, message: '请选择考试阅卷方式', trigger: 'change' }],
  'markingConfig.questionBasicMarkingUsers': [{ required: true, message: '请选择大题阅卷人', trigger: 'change' }],
  'markingConfig.subQuestionBasicMarkingUsers': [{ required: true, message: '请选择小题阅卷人', trigger: 'change' }],
  'markingConfig.markingAdmins': [{ required: true, message: '请选择阅卷管理员', trigger: 'change' }],
  'markingConfig.assignStrategy': [{ required: true, message: '请选择评卷任务分配方式', trigger: 'change' }],
  'markingConfig.scoringMode': [{ required: true, message: '请选择赋分方式', trigger: 'change' }],

}
const props = ref({ multiple: true })
// 考试信息编辑
const dialogVisible = ref(false);
const dialogTitle = ref("");
const defaultFormData = reactive({
  name: "",
  description: "",
  openType: "",
  businessKey: "",
  totalScore: 100,
  qualifyScore: 60,
  enrollStartTime: "",
  enrollEndTime: "",
  startTime: "",
  endTime: "",
  timeLimit: true,
  duration: 90,
  tryCount: 1,
  answerMode: "",  //答题模式,可用值:ONE_BY_ONE(one_by_one,逐题模式),ALL_AT_ONCE(all_at_once,整卷模式)
  autoComposingTime: "",
  paperConfig: {
    isItemRandom: false,
    label: "",
    randomWay: '1',
    useArbitration: false,
    arbitrationRate: 0,
    arbitrationScore: 0,
    customizationVo: {
      bankIdList: [],
      itemScore: 0,
      itemSetConfigVoList: [
        {
          setName: "",
          itemNum: 0,
          itemScore: 1,
          typeId: "",
          difficultyLevel: 0,
          useArbitration: false,
          arbitrationScore: 0,
        }
      ]
    },
    originFormVo: {
      isTitleRandom: false,
      originalIdList: []
    },
  },
  permissionConfig: {  //	权限规则
    accessMode: "",
    visibilityForOutRangeUser: true,
    password: "",
    allowDepartments: [],
    allowGroups: [],
    allowUsers: []
  },
  antiCheatingConfig: { //反作弊控制
    antiCheatBaseConfig: {  //基础控制
      deviceUseRestriction: {  //设备使用限制
        open: true,
        monitoringDelivery: true,
        allowPc: true,
        allowMobile: true
      },
      deviceSwitchingRestriction: {  //设备切换限制
        open: true,
        monitoringDelivery: true,
        allowDeviceSwitch: true,
        maxSwitchCount: 0
      },
      ipSwitchingRestriction: {  //IP切换限制
        open: true,
        monitoringDelivery: true,
        allowIpChange: true,
        maxIpChangeCount: 0
      },
      additionalRestriction: {  //试卷控制
        open: true,
        monitoringDelivery: true,
        copyPrevent: true,
        watermark: true,
        fullScreen: true
      }
    },
    antiCheatMonitorConfig: {  //监控配置
      screenAndCameraMonitorConfig: {  //屏幕&摄像头监控配置
        open: true,
        monitoringDelivery: true,
        screenRealTimeStream: true,
        cameraRealTimeStream: true,
        screenRecordOpen: true,
        cameraRecordOpen: true
      },
      behaviorMonitoringConfig: {  //行为监控配置
        open: true,
        monitoringDelivery: true,
        behaviorMonitoringInterval: 0,
        behaviorMonitoringThreshold: 0
      },
      faceMonitoringConfig: {  //人脸监控配置
        open: true,
        monitoringDelivery: true,
        faceMonitoringInterval: 0,
        faceMonitoringThreshold: 0
      },
      soundMonitoringConfig: {  //声音监控配置
        open: true,
        monitoringDelivery: true,
        soundMonitoringInterval: 0,
        soundMonitoringThreshold: 0
      },
      noActionMonitoringConfig: {  //无操作监控配置
        open: true,
        monitoringDelivery: true,
        noActionMonitoringInterval: 0,
        noActionMaxDuration: 0
      },
      windowsSwitchMonitoringConfig: {  //窗口切换监控配置
        open: true,
        monitoringDelivery: true,
        windowsSwitchMonitoringInterval: 0,
        windowsSwitchMaxCount: 0
      }
    }
  },
  // antiCheatingConfig:{  //防作弊规则
  //   antiCheatBaseConfig:{  //设备控制
  //     allowPc: true,
  //     allowMobile: true,
  //     allowDeviceSwitch: true,
  //     maxSwitchCount: 2,
  //     allowIpChange: true,
  //     maxIpChangeCount: 2,
  //     copyPrevent: true,
  //     watermark: true,
  //     fullScreen: true,  //全屏显示
  //   },
  //   antiCheatMonitorConfig:{  //监控配置
  //     screenRecordOpen: true,
  //     requireAuxiliaryMonitor: true,
  //     faceCheckOpen: true,
  //     faceCheckInterval: true,
  //     faceCheckThreshold: 30,
  //     noActionMonitorOpen: true,
  //     noActionMaxDuration: 10,
  //     windowsSwitchMonitorOpen: true,
  //     windowsSwitchMaxCount: 2,
  //   }
  // },
  invigilatorConfig: {  //监考规则
    invigilatorGroup: ""
  },
  markingConfig: {  //评卷配置
    markingType: "",
    markingStartTime: "",
    markingEndTime: "",
    hideAnswererName: true,
    markingMethod: "",
    markingUsers: [],
    markingAdmins: [],
    multiRound: true,
    markingRound: 1,
    assignStrategy: "",
    scoringMode: "",
    autoRecycle: true,
    autoRecycleTime: 0
  },
  resultDisplayConfig: {  //考试结果展示配置
    showScore: true,
    showCorrectAnswer: true,
    showAnswerCard: true,
    showAnswer: true
  },
  certificateConfigs: [  //证书规则 默认为空
    // {
    //   beginScore: 0,
    //   includeBeginScore: true,
    //   endScore: 0,
    //   includeEndScore: true,
    //   certificateTemplateId: ""
    // }
  ]
});
const formData = ref(defaultFormData);
//添加证书
const addCertificate = () => {
  if(!Array.isArray(formData.value.certificateConfigs)){
    formData.value.certificateConfigs = [];
  }
  formData.value.certificateConfigs.push({
    beginScore: 0,
    includeBeginScore: true,
    endScore: 0,
    includeEndScore: true,
    certificateTemplateId: ""
  });
}
//删除证书
const delcertificate = (index) => {
  formData.value.certificateConfigs.splice(index, 1);
};

//创建考试
const addExam = () => {
  dialogVisible.value = true;
  dialogTitle.value = "创建考试";
  formData.value = defaultFormData;
}

//导航滚动设置
const contentRef = ref(null); 
const asyncRef = ref(null); 

// 分别定义每个内容区域的 ref
const sectionRef0 = ref(null);
const sectionRef1 = ref(null);
const sectionRef2 = ref(null);
const sectionRef3 = ref(null);
const sectionRef4 = ref(null);
const sectionRef5 = ref(null);
const sectionRef6 = ref(null);
const sectionRef7 = ref(null);

const syncSectionRef0 = ref(null)
const syncSectionRef1 = ref(null)
const syncSectionRef2 = ref(null)
const syncSectionRef3 = ref(null)

const sections = ref([
  sectionRef0,
  sectionRef1,
  sectionRef2,
  sectionRef3,
  sectionRef4,
  sectionRef5,
  sectionRef6,
  sectionRef7
]);
const syncSections = ref([
  syncSectionRef0,
  syncSectionRef1,
  syncSectionRef2,
  syncSectionRef3
]);
const activeIndex = ref(0);
// 点击导航项，滚动到对应内容区域
const scrollToSection = (index) => {
  let section
  if(dialogVisible.value){
    section = sections.value[index].value;
  } else if(editExamDialog.value) {
    section = syncSections.value[index].value;
  }
  if (section) {
    section.scrollIntoView({
      behavior: 'smooth',
      block: 'start'
    });
    activeIndex.value = index;
  } else {
    console.error(`Section ${index} not found`);
  }
};

// 处理滚动事件，更新激活的导航项
const handleScroll = () => {
  let scrollTop = 0;
  if (contentRef.value && dialogVisible.value) {
    scrollTop = contentRef.value.scrollTop;
  } else if (asyncRef.value && editExamDialog.value) {
    scrollTop = asyncRef.value.scrollTop;
  }
  let currentIndex = 0;
  // 遍历所有内容区域，找到当前激活的区域
  let tempSelect = []
  if(dialogVisible.value){
    tempSelect = sections.value;
  } else if(editExamDialog.value) {
    tempSelect = syncSections.value;
  }
  for (let i = tempSelect.length - 1; i >= 0; i--) {
    const section = tempSelect[i].value;
    if (section && section.offsetTop <= scrollTop + 50) {
      currentIndex = i ;
      break;
    }
  }
  if (activeIndex.value !== currentIndex) {
    activeIndex.value = currentIndex;
    // console.log(currentIndex);
    
  }
};

// 计算 flex-box 的高度
const sectionHeight = ref(0); // 响应式变量存储高度
let resizeObserver = null;
const flexBoxStyle = computed(() => {
  if (sectionRef7.value) {
    const maxHeight = `calc(100vh - 148px - ${sectionHeight.value}px)`;
    return { height: maxHeight };
  }
  console.log('sectionRef7 未定义');
  return {};
});

watch(() => sectionRef7, (newVal) => {
  if (newVal) {
    // 创建 ResizeObserver 监听尺寸变化
    resizeObserver = new ResizeObserver((entries) => {
      console.log('ResizeObserver 触发, entries.length:', entries.length);
      for (const entry of entries) {
        const newHeight = entry.target.offsetHeight;
        sectionHeight.value = newHeight; // 更新响应式变量
      }
    });
    resizeObserver.observe(sectionRef7.value); // 开始监听
  } else {
    if (resizeObserver) {
      resizeObserver.disconnect(); // sectionRef7不存在时停止监听
    }
  }
}, { deep: true });

onMounted(() => {
  nextTick(() => {
    handleScroll(); // 初始化时计算一次
  });
});

// onUnmounted(() => {
//   if (resizeObserver) {
//     resizeObserver.disconnect(); // 组件卸载时停止监听
//   }
// });
const formRef = ref(null)
const ayncFormRef = ref(null)

//关闭对话框
const handleCloseDialog = () => { 
  console.log("关闭对话框");
  ElMessageBox.confirm('是否保存设置', '提示', {
    distinguishCancelAndClose: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    if(dialogVisible.value){
      handleSubmit()
    } else if(editExamDialog.value){
      postSync()
    }
  }).catch(() => {
    dialogVisible.value = false;
    editExamDialog.value = false;
    contentRef.value.scrollTop = 0;
  })
};

//更改考试状态 如果是设为发布时需要检查考试配置是否正常
const changeState = async (item,state) => {
  if (state) {
    if(state === 'NORMAL(normal,正常)'){
      ElMessageBox.confirm('请检查考试设置是否正常', '发布考试', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        const res = await checkPaperConfigExam(item);
        if(res.code === 20000){
          ElMessage.success("操作成功");
          getTableData();
        }
      }).catch((error) => {
        console.log("error",error);
      })
    } else {
      const res = await changeExamStatusExam({
        examId: item.id,
        examStatus: state
      });
      if (res.code === 20000) {
        ElMessage.success("操作成功");
        getTableData();
      }
    }
  }
}

//复制考试
const copyExam = async (item) => {
  const res = await copyAndNewExam({
    examId: item.id
  });
  if(res.code === 20000){
    formData.value = res.data;
    dialogVisible.value = true;
    ElMessage.success("复制成功");
    getTableData();
  }
}
//编辑考试
const editExam = async (item) => {
  // const res = await getExamExam({ examId: item.id });
  // if (res.code === 20000) {
    dialogVisible.value = true;
    dialogTitle.value = "编辑考试";
    formData.value = { ...item };
    formData.value.paperConfig = JSON.parse(formData.value.paperConfig);
    // formData.value = res.data;
    // theNumber.value = 1;
    // activeNumber.value = 7;
    // formData.value.startTime = convertedDate(formData.value.startTime,' ','T');
    // formData.value.endTime = convertedDate(formData.value.endTime,' ','T');
  // }
}

//删除考试
const delExam = async (item) => {
  ElMessageBox.confirm('确定删除该考试吗？', '提示', {
    distinguishCancelAndClose: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const res = await deleteExamExam({ examId: item.id });
    if (res.code === 20000) {
      ElMessage.success("删除成功");
      getTableData();
    }
  })
}

//暂存考试
const stagingSubmit = async () => {
  //将提交数据中的时间改为标准时间格式
  if (formData.value.startTime) {
    formData.value.startTime = formatDate(formData.value.startTime,"yyyy-MM-dd hh:mm:ss");
  }
  if (formData.value.endTime) {
    formData.value.endTime = formatDate(formData.value.endTime,"yyyy-MM-dd hh:mm:ss");
  } 
  if (formData.value.autoComposingTime) {
    formData.value.autoComposingTime = formatDate(formData.value.autoComposingTime,"yyyy-MM-dd hh:mm:ss");
  } 
  if (formData.value.paperConfig && formData.value.paperConfig != "") {
    formData.value.paperConfig = JSON.stringify(formData.value.paperConfig);
  } 
  const res = await stagingExam(formData.value);
  if (res.code === 20000) {
    ElMessage.success("暂存考试成功");
    dialogVisible.value = false;
    formData.value = defaultFormData;
    getTableData();
  }
}
//提交考试
const handleSubmit = async () => {
  const formEl = formRef.value;
  if (!formEl){
    ElMessage.warning("请填写完整考试必填信息");
    return;
  } 
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      //将提交数据中的时间改为标准时间格式
      if (formData.value.startTime) {
        formData.value.startTime = formatDate(formData.value.startTime,"yyyy-MM-dd hh:mm:ss");
      }
      if (formData.value.endTime) {
        formData.value.endTime = formatDate(formData.value.endTime,"yyyy-MM-dd hh:mm:ss");
      } 
      if (formData.value.autoComposingTime) {
        formData.value.autoComposingTime = formatDate(formData.value.autoComposingTime,"yyyy-MM-dd hh:mm:ss");
      } 
      if (formData.value.paperConfig && formData.value.paperConfig != "") {
        formData.value.paperConfig = JSON.stringify(formData.value.paperConfig);
      } 
      //选择部门需要单独处理
      if (formData.value.permissionConfig.allowDepartments) { 
        console.log(formData.value.permissionConfig.allowDepartments);
      }
      if (dialogTitle.value === "创建考试") {
        const res = await createExam(formData.value);
        if (res.code === 20000) {
          ElMessage.success("新增考试成功");
        }
      } else if(dialogTitle.value === "编辑考试") {
        const res = await updateExam(formData.value);
        if (res.code === 20000) {
          ElMessage.success("编辑考试成功");
        }
      }
      dialogVisible.value = false;
      formData.value = defaultFormData;
      getTableData();
    } else {
      console.log('error submit!', fields);
      return;
    }
  })
}
 
const disabledEndDate = (time) => {
  if (formData.value.startTime) {
    // 将 startTime 转换为 Date 对象
    const start = new Date(formData.value.startTime);
    start.setDate(start.getDate() - 1);
    // 禁用早于开始时间的日期
    return time.getTime() < start.getTime();
  }
  return false;
};

const syncDefaultForm = reactive({
  examIds: [],
  startTime: "",
  endTime: "",
  timeLimit: false,
  duration: 90,
  tryCount: 1,
  accessMode: "",
  answerMode: "",
  antiCheatingConfig: {
    antiCheatBaseConfig: {
      allowPc: true,
      allowMobile: true,
      allowDeviceSwitch: true,
      maxSwitchCount: 0,
      allowIpChange: true,
      maxIpChangeCount: 0,
      copyPrevent: true,
      watermark: true,
      fullScreen: true
    },
    antiCheatMonitorConfig: {
      screenRecordOpen: true,
      requireAuxiliaryMonitor: true,
      faceCheckOpen: true,
      faceCheckInterval: true,
      faceCheckThreshold: 0,
      noActionMonitorOpen: true,
      noActionMaxDuration: 0,
      windowsSwitchMonitorOpen: true,
      windowsSwitchMaxCount: true
    }
  },
  resultDisplayConfig: {
    showScore: true,
    showCorrectAnswer: true,
    showAnswerCard: true,
    showAnswer: true
  }
})
const syncForm = ref({...syncDefaultForm})

const editExamDialog = ref(false)
const batchSync = async () => {
  editExamDialog.value = true
 
}
const postSync = async () =>{
  const formEl = ayncFormRef.value;
  if (!formEl){
    ElMessage.warning("请填写完整考试必填信息");
    return;
  }  
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      syncForm.value.examIds = checkedList.value;
      if (syncForm.value.startTime) {
        syncForm.value.startTime = formatDate(syncForm.value.startTime,"yyyy-MM-dd hh:mm:ss");
      }
      if (syncForm.value.endTime) {
        syncForm.value.endTime = formatDate(syncForm.value.endTime,"yyyy-MM-dd hh:mm:ss");
      }
      syncExamsConfigExam(syncForm.value).then((res) => {
        if (res.code === 20000) {
          ElMessage.success("考试设置同步成功");
          getTableData();
          editExamDialog.value = false
          syncForm.value = {...syncDefaultForm}
          // isAllSearch.value = false;
          isAllChooseBtn.value = false;
          checkedList.value = [];
        }
      });
    } else {
      ElMessage.warning("请填写完整考试必填信息");
      console.log('error submit!', fields);
      return;
    }
  })
}
// 批量操作
const batchOptions = ref([
  { name: "同步配置", value: "sync", icon: "&#xe6e6;" },
]);
const handleBatchOptions = (data) => {
  if (data === "sync") {
    batchSync();
  } 
};

//获取部门树
const departTree = ref([]);
const transformData = (data) => {
  return data.map(item => {
    const transformedItem = {
      value: item.id,
      label: item.name
    };

    if (item.children && item.children.length > 0) {
      transformedItem.children = transformData(item.children);
    }
    return transformedItem;
  });
};
const getDepartData = async () => {
  const res = await getDepartTree({departId: "root"});
  if (res.code === 20000) {
    departTree.value = transformData(res.data.children)
  }
};

//获取分组
const groupList = ref([])
const getGroupData = async () => {
  const res = await pagingGroup({ 
    currentPage: 1,
    pageSize: 100
  });
  groupList.value = res.data.list;
};

const fieldList = ref([
  {
    title: "名称",
    name: "name",
  },
  {
    title: "说明",
    name: "description",
  },
  {
    title: "状态",
    name: "status",
  },
  {
    title: "访问模式",
    name: "accessMode",
  },
  {
    title: "开始时间",
    name: "startTime",
    visible: true,
  },
  {
    title: "结束时间",
    name: "endTime",
    visible: true,
  },
  {
    title: "考试时长(分钟)",
    name: "duration",
    visible: true,
  },
  {
    title: "总分",
    name: "totalScore",
    visible: true,
  },
  {
    title: "及格分数",
    name: "qualifyScore",
    visible: true,
  },
  {
    title: "操作",
    name: "options",
    width: 250,
    fixed: "right",
  },
]);

onMounted(async() => {
  await getTableData();
  await getDepartData();
  await getGroupData();
});
</script>

<style scoped lang="scss">
.top-btns{
  display: flex;
  margin: 10px 0;
  justify-content: space-between;
  /* align-items: center; */
  .add-button{
    margin-right: 10px;
  }
}

::v-deep .el-step.is-simple .el-step__title{
  font-size: 14px;
}

.step-item{
  cursor: pointer;
  &.cur{
    font-weight: bold;
  }
}

::v-deep .el-step.is-simple:not(:last-of-type) .el-step__title {
  width: max-content;
  max-width: 90%;
}

.table-td-option{
  display: flex;
  align-items: center;
}

.exam-draw{
  /* width: 800px; */
  display: flex;
  &.tips{
    .menu-list{
      top: 85px;
    }
  }
  .menu-list{
    display: flex;
    flex-direction: column;
    /* position: fixed;
    top: 65px;
    left: 20px; */
    .step-item{
      margin-bottom: 10px;
      font-size: 16px;
      color: $black_2;
      &.cur{
        font-weight: bold;
        color: $mainColor;
      }
    }
  }
  .exam-form{
    margin-left: 120px;
  }
  .exam-info{
    margin-bottom: 20px;
    border: 1px solid $borderColor;
    box-shadow: 0 0 10px rgba(black,.1);
    padding: 20px;
    box-sizing: border-box;
    border-radius: 10px;
    min-width: 500px;
    width: 520px;
    h3{
      margin-bottom:  10px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .certificate-item{
      margin: 10px 0;
      padding: 15px 15px 0;
      box-sizing: border-box;
      border: 1.5px dashed #bbb;
      border-radius: 5px;
    }
    .form-item-tip{
      color: $black_2;
    }
    .form-row{
      display: flex;
      align-items: center;
      justify-content: space-between;
      flex-wrap: wrap;

      .row-item{
        width: 50%;
      }
      .del-icon{
        font-size: 18px;
        color: #e85252;
        margin-bottom: 15px;
        &:hover{
          color: #e52c2c;
        }
      }
    }
  }
}
.sync-exam-container{
  display: flex;
  flex-direction: column;
  height: 100%;
  .tip{
    font-size: 14px;
    margin-bottom: 10px;
    color: $mainColor;
  }
  .exam-container{
    display: flex;
    flex: 1;
    overflow: hidden;
    position: relative;
    .menu-list{
      width: 100px;
      display: flex;
      flex-direction: column;
      position: absolute;
      left: 0;
      top: 0;
      .step-item{
        margin-bottom: 10px;
        font-size: 16px;
        color: $black_2;
        &.cur{
          font-weight: bold;
          color: $mainColor;
        }
      }
    }
    .exam-draw{
      height: 100%;
      .exam-form{
        margin-left: 120px;
      }
    }
  }
}
.question-group-config{
  width: 480px;
  .tip{
    margin-top: 10px ;
    color: $black;
    font-size: 14px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .item-set-config{
    margin-top: 10px ;
    padding: 15px 15px 0;
    box-sizing: border-box;
    border: 1.5px dashed #bbb;
    border-radius: 5px;
    /* box-shadow: 0 0 10px rgba(0,0,0,0.1); */
    .form-row{
      display: flex;
      align-items: center;
      justify-content: space-between;
      .row-item{
        width: 50%;
      }
      .del-icon{
        font-size: 18px;
        color: #e85252;
        margin-bottom: 15px;
        &:hover{
          color: #e52c2c;
        }
      }
    }
  }
  
}

</style>